package org.example.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.model.Result;
import org.example.util.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class UserTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入到了拦截器用户");
        //获得token
        String userToken  =  request.getHeader("userToken");
        System.out.println("token:"+userToken);

        if(JWTUtil.verify(userToken)){
            return true; //拦截器中返回true, 请求就会离开拦截器,继续向后执行,到达处理器
        }else{
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            Result result = new Result(401,"token验证失败",null);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(result);
            writer.write(json);
            return false;//拦截器中返回false. 不会继续向后执行.  可以在拦截器中向用户做出响应
        }
    }
}
